package com.xiang.controller;

import com.xiang.pojo.User;
import com.xiang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/9/28 1:00
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    //登录验证
    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, Model model, HttpServletRequest request, User user) {
        HttpSession session = request.getSession();
        session.setAttribute("UserSession", user);
//        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        if (userService.logincheck(user) != null) {
            model.addAttribute("username", username);
            return "redirect:/list";
        } else {
            model.addAttribute("error", "账号或密码错误");
            return "index";
        }
    }

    //注册
    @RequestMapping("/register")
    public String register(@RequestParam String username,@RequestParam String password, Model model) {
        User user = new User();
        System.out.println("执行");
        String s = userService.checkUserName(username);
        System.out.println("s"+s);
        if(s==null){
            user.setUsername(username);
            user.setPassword(password);
            userService.register(user);
            return "redirect:/list";
        }else {
            model.addAttribute("fail","该用户存在");
            System.out.println("该用户存在");
            return "/register";
        }

    }

    //注销
    @RequestMapping(value = "/logout")
    public String getLogout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.removeAttribute("UserSession");
        }
        return "index";

    }

}

